package cn.bincker.mycaptcha.basic.impl;

import cn.bincker.mycaptcha.basic.CaptchaGuard;
import cn.bincker.mycaptcha.CaptchaVerifier;
import cn.bincker.mycaptcha.basic.properties.MyCaptchaProperties;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 默认守卫
 */
public class DefaultCaptchaGuard implements CaptchaGuard {
    private final MyCaptchaProperties properties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final CaptchaVerifier captchaVerifier;

    public DefaultCaptchaGuard(MyCaptchaProperties properties, CaptchaVerifier captchaVerifier) {
        this.properties = properties;
        this.captchaVerifier = captchaVerifier;
    }

    @Override
    public boolean match(HttpServletRequest request) {
        var requestPath = request.getRequestURI();
        return !antPathMatcher.match(properties.getPath(), requestPath) && isProtectRequest(requestPath);
    }

    @Override
    public void check(HttpServletRequest request, HttpServletResponse response) {
        captchaVerifier.verify(request, response);
    }

    /**
     * 是否是需要保护的请求
     */
    private boolean isProtectRequest(String requestPath){
        for (var path : properties.getProtectPathList()) {
            if(antPathMatcher.match(path, requestPath)) return true;
        }
        return false;
    }
}
